﻿
using System.IO;

namespace ThingsGateway.Foundation
{
    /// <summary>
    /// 根据文件的大小来存储日志信息
    /// </summary>
    public class LogNetFileSize : LogNetFileBase
    {
        #region Private Fields

        private int currentFileSize = 0;
        public int FileMaxSize { get; set; } = 2 * 1024 * 1024;

        private string fileName = string.Empty;

        #endregion Private Fields

        #region Public Constructors

        /// <summary>
        /// 根据文件大小生成新文件
        /// </summary>
        /// <param name="filePath">日志文件的保存路径</param>
        /// <param name="FileMaxSize">每个日志文件的最大大小，默认2M</param>
        /// <param name="fileQuantity">日志文件数量上限</param>
        public LogNetFileSize(string filePath, int fileMaxSize = 2097152, int fileQuantity = -1)
        {
            FilePath = filePath;
            FileMaxSize = fileMaxSize;
            FileQuantity = fileQuantity;
            if (string.IsNullOrEmpty(filePath) || Directory.Exists(filePath))
            {
                return;
            }

            Directory.CreateDirectory(filePath);
        }

        #endregion Public Constructors

        #region Public Methods

        public override string GetFileSaveName()
        {
            if (string.IsNullOrEmpty(FilePath))
            {
                return string.Empty;
            }

            if (string.IsNullOrEmpty(fileName))
            {
                fileName = GetLastAccessFileName();
            }

            if (File.Exists(fileName))
            {
                FileInfo fileInfo = new FileInfo(fileName);
                if (fileInfo.Length > FileMaxSize)
                {
                    fileName = GetDefaultFileName();
                }
                else
                {
                    currentFileSize = (int)fileInfo.Length;
                }
            }
            return fileName;
        }

        public override string ToString()
        {
            return string.Format(nameof(LogNetFileSize) + "[{0}]", FileMaxSize);
        }

        #endregion Public Methods

        #region Private Methods

        /// <summary>
        /// 获取一个新的默认的文件名称
        /// </summary>
        /// <returns>完整的文件名</returns>
        private string GetDefaultFileName()
        {
            return Path.Combine(FilePath, "Logs_" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".txt");
        }

        /// <summary>
        /// 获取之前保存的日志文件
        /// </summary>
        /// <returns>文件名称</returns>
        private string GetLastAccessFileName()
        {
            foreach (string existLogFileName in GetLogFileNames())
            {
                FileInfo fileInfo = new FileInfo(existLogFileName);
                if (fileInfo.Length < FileMaxSize)
                {
                    currentFileSize = (int)fileInfo.Length;
                    return existLogFileName;
                }
            }
            return GetDefaultFileName();
        }

        #endregion Private Methods

    }
}